﻿namespace FitnessTracker.Calculators
{
    using System;

    public class RollingAccumulator<TReturn> where TReturn : IComparable 
    {
        private readonly TReturn accumulaitonPriorToCommensingMonitoring;
        private readonly uint rollingUpperRange;
        private TReturn lastValueReceivedInMeters;
        private uint numberOfRollOverEvents;
        
        public RollingAccumulator(TReturn accumulatoinToToCommensingMonitoring, uint rollingUpperRange)
        {
            this.accumulaitonPriorToCommensingMonitoring = accumulatoinToToCommensingMonitoring;
            this.rollingUpperRange = rollingUpperRange;
        }

        public TReturn Calculate(TReturn currentValue)
        {
            if (currentValue.CompareTo(this.lastValueReceivedInMeters) > 0)
            {
                this.numberOfRollOverEvents++;
            }

            this.lastValueReceivedInMeters = currentValue;

           return ((this.numberOfRollOverEvents * rollingUpperRange) + (dynamic)currentValue) 
               - this.accumulaitonPriorToCommensingMonitoring;
        }
    }
}
